@(formAddGame: Form[Kiry.AddNewGame], platformOptions: Seq[(String, String)])
@import helper._
@implicitField = @{ FieldConstructor(formCustom.f) }

@main("Ajouter un jeu", "newgame") {

    <script xmlns="http://www.w3.org/1999/html">
        var updateGameListTimeout;
        $(document).ready(function() {
            $("#releaseDate").pickadate({
                format: 'dd / mm / yyyy',
                formatSubmit: 'yyyy-mm-dd'
            });

            $("#searchGame").keydown(function() {
                clearTimeout(updateGameListTimeout);
                updateGameListTimeout = setTimeout(updateGameList, 400);
            });

            $.get("/getGenresList", function(data) {
                $('#genres').typeahead({
                    source: JSON.parse(data),
                    suppressKeyPressRepeat: true,
                    updater: function(tag) {
                        this.$element.data('tagmanager').create([ tag ]);
                        this.hide();
                    }
                });
            });

            $.get("/getCompagniesList", function(data) {
                $('.compagnies').typeahead({
                    source: JSON.parse(data),
                    suppressKeyPressRepeat: true
                });
            });

            $("#genres").tagmanager({
                strategy: 'array',
                tagFieldName: 'genres[]',
                suppressKeyPressRepeat: true,
                validateHandler: function(tagManager, tag, isImport) {
                    if (isImport) return tag;
                    var index = $.inArray(tag, tagManager.tagStrings);
                    if (index != -1) {
                        $('#' + tagManager.tagIds[index]).effect("highlight", {}, 3000);
                        return false;
                    }
                    return tag;
                }
            });
        });

        updateGameList = function() {
            $("#auto-fill").empty();
            var gameTitle = $("#searchGame").val();
            if (gameTitle == "" || gameTitle.length < 2)
                return;
            $("#auto-fill").html('<div><h5 style="display: inline;">Puis choisissez le jeu dans la liste</h5> <small>(actuellement vous ne pouvez qu\'ajouter des jeux qui apparaissent dans cette liste)</small></div><br>');
            showLoading();
            var link = "/getGameList/" + gameTitle;
            $.get(link, function(data) {
                $(data).find("game").each(function() {
                    var id = $(this).find("id").text();
                    var gameTitle = $(this).find("GameTitle").text();
                    var plateform = $(this).find("Platform").text();
                    var releaseDate = $(this).find("ReleaseDate").text();
                    releaseDate = releaseDate.split("/");
                    releaseDate = releaseDate[1]+"/"+releaseDate[0]+"/"+releaseDate[2];
                    $("#auto-fill").append("<a href='javascript:updateGameInfo("+id+")'><div class='auto-fill-game'><span>" + gameTitle + "</span><span>" + releaseDate + "<br>" + plateform + "</span></div></a>");
                });
                hideLoading();
                $("#auto-fill a").first().css("zoom", "1.2");
                $("<h5>Meilleur résultat</h5>").insertBefore( $("#auto-fill a").first());
                $("<h5>Autres résultats</h5>").insertAfter( $("#auto-fill a").first());
            });
        }

        updateGameInfo = function(idGame) {
            showLoading();
            var link = "/getGameInfo/" + idGame;
            $.get(link, function(data) {
                $(data).find("game").each(function() {
                    var id = $(this).find("id").text();
                    var gameTitle = $(this).find("GameTitle").text();
                    var platform = $(this).find("PlatformId").text();
                    var youtube = $(this).find("youtube").text();
                    var rating = Math.round($(this).find("Rating").text() * 10);
                    var releaseDate = $(this).find("ReleaseDate").text();
                    releaseDateSplit = releaseDate.split("/");
                    releaseDate = releaseDateSplit[1]+" / "+releaseDateSplit[0]+" / "+releaseDateSplit[2];
                    releaseDate_submit = releaseDateSplit[2]+"-"+releaseDateSplit[0]+"-"+releaseDateSplit[1];
                    var publisher = $(this).find("Publisher").text();
                    var developer = $(this).find("Developer").text();
                    $("#idGameDb").val(id);
                    $("#gameTitle").val(gameTitle);
                    $("#game-title-label").html(gameTitle);
                    $("#youtube").val(youtube);
                    $("#releaseDate").val(releaseDate);
                    $("input[name='releaseDate_submit']").val(releaseDate_submit);
                    $("#rating").val(rating);
                    $("#platform").val(platform);
                    $("#publisher").val(publisher);
                    $("#developer").val(developer);

                    // Populate genres tags
                    $("#genres").data('tagmanager').empty();
                    $(this).find("genre").each(function() {
                        $("#genres").data('tagmanager').populate([$(this).text()]);
                    });
                    hideLoading();
                    goToStepTwo();
                });
            });
        }

        backToStepOne = function() {
            $("#input-extra-informations").hide(300);
            $("#first-step").show(300);
        }

        goToStepTwo = function() {
            $("#first-step").hide(300);
            $("#input-extra-informations").show(300);
        }
    </script>
    <div style="margin-top: 50px;">

        <div id="first-step">
            <h5>Pour commencer entrez le nom du jeu à ajouter</h5>
            <input type="text" id="searchGame" placeholder="Titre du jeu">
            <div id="auto-fill"></div>
        </div>

        @helper.form(routes.Kiry.addNewGame, 'id -> "form-add-new-game") {
            @if(formAddGame.hasGlobalErrors) {
                <p class="error">
                    @formAddGame.globalError.message
                </p>
            }

            <div id="input-extra-informations">
                <nobr><h5 style="font-size: 50px; margin-bottom: 20px;" id="game-title-label"></h5></nobr>
                <h5>Complétez ou modifier les informations puis cliquez sur le bouton ajouter en haut de la page</h5>
                <label for="gameTitle">Titre du jeu</label>
                @inputText(formAddGame("gameTitle"), 'placeholder -> "Titre", 'type -> "text", 'autocomplete -> "off")
                <label for="youtube">Lien d'une bande annonce youtube</label>
                @inputText(formAddGame("youtube"), 'placeholder -> "Youtube", 'type -> "text", 'autocomplete -> "off")
                <label for="rating">Note (sur 100)</label>
                @inputText(formAddGame("rating"), 'placeholder -> "Note", 'type -> "number")
                <label for="releaseDate">Date de sortie</label>
                <input type="text" id="releaseDate" name="releaseDate" value="" placeholder="Date de sortie" readonly="readonly">
                <label for="platform">Console</label>
                @select(formAddGame("platform"), options = platformOptions)
                <label for="genres">Genres (plusieurs possibles)</label>
                @inputText(formAddGame("genres"), 'placeholder -> "Genres", 'class -> "tagManager", 'autocomplete -> "off")
                <div class="wrap-compagnies">
                    <div>
                        <label for="developer">Développeur</label>
                        @inputText(formAddGame("developer"), 'placeholder -> "Developpeur", 'autocomplete -> "off", 'class -> "compagnies")
                    </div>
                    <div>
                        <label for="publisher">Éditeur</label>
                        @inputText(formAddGame("publisher"), 'placeholder -> "Editeur", 'autocomplete -> "off", 'class -> "compagnies")
                    </div>
                </div>
                @inputText(formAddGame("idGameDb"), 'type -> "hidden")
                <a href="javascript:backToStepOne()">changer de jeu</a>
            </div>
        }
    </div>
}